<?php

declare(strict_types=1);

namespace App\Controller;

use Hyperf\SocketIOServer\Annotation\Event;
use Hyperf\SocketIOServer\Annotation\SocketIONamespace;
use Hyperf\SocketIOServer\BaseNamespace;
use Hyperf\SocketIOServer\Socket;
use Hyperf\Di\Annotation\Inject;
use Psr\Container\ContainerInterface;
use Psr\EventDispatcher\EventDispatcherInterface;
use App\Event\UserChat;
use App\Event\SocketIoConnect;
use App\Event\SocketIoDisConnect;
use App\Event\SendWelcomeMsg;

/**
 * @SocketIONamespace("/")
 */
class WebSocketController extends BaseNamespace
{
    /**
     * @Inject
     * @var ContainerInterface
     */
    protected $container;

    /**
     * @Inject 
     * @var EventDispatcherInterface
     */
    private $eventDispatcher;

    /**
     * @Event("connect")
     */
    public function connect(Socket $socket)
    {
        $user = $socket->getRequest()->getAttribute('user');
        // 这里 dispatch(object $event) 会逐个运行监听该事件的监听器
        $this->eventDispatcher->dispatch(new SocketIoConnect($user, $socket->getSid()));
    }

    /**
     * @Event("disconnect")
     */
    public function disconnect(Socket $socket)
    {
        $user = $socket->getRequest()->getAttribute('user');
        // 这里 dispatch(object $event) 会逐个运行监听该事件的监听器
        $this->eventDispatcher->dispatch(new SocketIoDisConnect($user));
    }

    /**
     * @Event("sendmsg")
     * @param string $data
     */
    public function onSay(Socket $socket, $data)
    {
        $user = $socket->getRequest()->getAttribute('user');
        // 这里 dispatch(object $event) 会逐个运行监听该事件的监听器
        $this->eventDispatcher->dispatch(new UserChat($user, $data));
    }

    /**
     * @Event("welcome_msg")
     * @param string $data
     */
    public function onWelcomeMsg(Socket $socket, $data)
    {
        $user = $socket->getRequest()->getAttribute('user');
        // 这里 dispatch(object $event) 会逐个运行监听该事件的监听器
        $this->eventDispatcher->dispatch(new SendWelcomeMsg($user, $data));
    }
}